ストア Vue.js
What is a Store?
A Store (like Pinia) is an entity holding state and business logic that isn't bound to your Component tree. In other words, it hosts global state.
-> global state
簡単な global state
code:store.js
import { reactive } from "vue";
export const store = reactive({ count: 0 });
この store.js を import すればよい
code:ComponentA.vue
<script setup>
import { store } from "./store.js";
</script>
<template>
From A: {{ store.count }}
</template>
code:ComponentB.vue
<script setup>
import { store } from "./store.js";
</script>
<template>
From B: {{ store.count }}
</template>
store オブジェクトの更新によって、ComponentA.vue, ComponentB.vue はそれぞれ自動的に view を更新する
-> "a single source of truth"(SSoT) import しているどんなコンポーネントでも好きなように store を更新できてしまう
code:ComponentX.vue
<template>
<button @click="store.count++">
From B: {{ store.count }}
</button>
</template>
メンテが大変になるので状態を更新する処理(action)も store にまとめて記述する
code:store.js
import { reactive } from "vue";
export const store = reactive({
count: 0;
inc : () => this.count++;
}):
code:ComponentX.vue
<template>
<button @click="store.inc()">
{{ store.count }}
</button>
</template>
When should I use a Store?
A store should contain data that can be accessed throughout your application. This includes data that is used in many places, e.g. User information that is displayed in the navbar, as well as data that needs to be preserved through pages, e.g. a very complicated multi-step form.